package com.uzhie.util;

import com.uzhie.web.module.Catalog;

import java.util.*;

/**
 * 逆向Tree工具,筛选出与原始列表有关系的列
 * Created by lilongfei on 2018/7/25.
 */
public class TreeBuildUtil {
    //原始树列表
    List<Catalog> origins;
    //末端节点
    List<Catalog> nodes;
    //两者筛选后的剩余结果
    MyArrayList result;


    public TreeBuildUtil() {
    }

    public TreeBuildUtil(List<Catalog> origin, List<Catalog> node) {
        this.origins = origin;
        this.nodes = node;
        this.result = new MyArrayList();
    }

    /**
     * 比对树状列表
     *
     * @return
     */
    public List<Catalog> filter() {
        result.addAll(nodes);
        origins.removeAll(nodes);
        for (Catalog catalog : nodes) {
            if (catalog.getParentId() != null) {
                getParent(catalog.getId(), catalog);
            }

        }
        Collections.sort(result, Comparator.comparing(Catalog::getLevel));
        return result;
    }

    /**
     * 获取节点父类,在保存的同时从原始列表中移除
     *
     * @param origin
     */
    public void getParent(String nodeId, Catalog origin) {
        Iterator<Catalog> iterator = origins.iterator();
        while (iterator.hasNext()) {
            Catalog catalog = iterator.next();
            if (origin.getParentId().equals(catalog.getId())) {
                if (!catalog.getId().equals(nodeId) && !result.containsKey(catalog.getId()))
                    result.add(catalog);
                if (catalog.getParentId() != null) {
                    getParent(nodeId, catalog);
                }
            }
        }
    }


    class MyArrayList extends ArrayList<Catalog> {
        public boolean containsKey(String id) {
            for (Catalog catalog : this) {
                if (catalog.getId().equals(id)) {
                    return true;
                }
            }
            return false;
        }
    }

    /**
     * 内部排序器
     */
    public class MyCompare implements Comparator<Catalog> {

        @Override
        public int compare(Catalog o1, Catalog o2) {
            return o1.getLevel().compareTo(o2.getLevel());
            //下面这样写会报错 Comparison method violates its general contract!
//            if (o1.getLevel() < o2.getLevel()) {
//                return -1;
//            } else {
//                return 1;
//            }
        }

    }
}
